var code = require('./code.js');
var moment  = require('moment');
var db = require('./db.js');
var request = require('request');
var async = require('async');
var dgram = require("dgram");

var sim_unicode_cache=[];
var res;
var vehicle_datas = [];

db.sequelize.query('select t.SIM ,v.UNIFICATIONCODE from T_TERMINAL t, T_VEHICLE v where t.TERMINALID = v.TERMINALID'
	, { type: db.sequelize.QueryTypes.select })
	.then(function (results){
		sim_unicode_cache = results[0];
		console.log(sim_unicode_cache);
	});

//解析位置回传消息体的主方法
var parsePosition = function(b,head){
	res = {};
	res.sim = head.TerminalPhoneNum;
	for (var i = 0; i < sim_unicode_cache.length; i++){
		if(sim_unicode_cache[i].SIM == head.TerminalPhoneNum){
			res.unificationcode = sim_unicode_cache[i].UNIFICATIONCODE;
			//console.log("当前报文唯一码"+res.unificationcode);
		}
	}
	console.log("tel:"+head.TerminalPhoneNum);
	res.wiringstatus = code.bytes2int4(b.slice(0,3));  //有待验证
	res.alarmData= '';
	//报警标志0-3
	if((b[3]&0x1)!=0){res.alarmData+='0,';}// 紧急报警0
	if((b[3]&0x2)!=0){res.alarmData+='1,';}// 超速报警1
	if((b[3]&0x4)!=0){res.alarmData+='2,';}// 疲劳驾驶2
	if((b[3]&0x8)!=0){res.alarmData+='3,';}// 危险预警3
	if((b[3]&0x10)!=0){res.alarmData+='4,';}// GNSS模块发生故障4
	if((b[3]&0x20)!=0){res.alarmData+='5,';}// GNSS天线未接或被剪断5
	if((b[3]&0x40)!=0){res.alarmData+='6,';}// GNSS天线短路6
	if((b[3]&0x80)!=0){res.alarmData+='7,';}// 主电压欠压7
	if((b[2]&0x1)!=0){res.alarmData+='8,';}// 终端主电源掉电 8
	if((b[2]&0x2)!=0){res.alarmData+='9,';}// 终端LCD或显示屏故障,9
	if((b[2]&0x4)!=0){res.alarmData+='10,';}// TTS模块故障,10
	if((b[2]&0x8)!=0){res.alarmData+='11,';}// 摄像头故障,11
	if((b[2]&0x10)!=0){res.alarmData+='12,';}//道路运输证IC卡模块故障,12
	if((b[2]&0x20)!=0){res.alarmData+='13,';}//超速预警,13
	if((b[2]&0x40)!=0){res.alarmData+='14,';}//疲劳驾驶预警,14
	if((b[1]&0x4)!=0){res.alarmData+='18,';}// 当天累计驾驶超时,18 (15-17预留)
	if((b[1]&0x8)!=0){res.alarmData+='19,';}// 超时停车,19
	if((b[1]&0x10)!=0){res.alarmData+='20,';}// 进出区域，20
	if((b[1]&0x20)!=0){res.alarmData+='21,';}// 进出路线，21
	if((b[1]&0x40)!=0){res.alarmData+='22,';}// 路段行驶时间不足/过长,22
	if((b[1]&0x80)!=0){res.alarmData+='23,';}// 路线偏离报警,23
	if((b[0]&0x1)!=0){res.alarmData+='24,';}// 车辆VSS故障,24
	if((b[0]&0x2)!=0){res.alarmData+='25,';}// 车辆油量异常,25
	if((b[0]&0x4)!=0){res.alarmData+='26,';}// 车辆被盗,26
	if((b[0]&0x8)!=0){res.alarmData+='27,';}// 车辆非法点火,27
	if((b[0]&0x10)!=0){res.alarmData+='28,';}// 车辆非法位移,28
	if((b[0]&0x20)!=0){res.alarmData+='29,';}// 碰撞预警,29
	if((b[0]&0x40)!=0){res.alarmData+='30,';}//侧翻预警,30
	if((b[0]&0x80)!=0){res.alarmData+='31,';}//非法开关门报警,31
	//状态4-7
	if((b[7]&0x1)!=0){
		res.acc = true;
	}else{
		res.acc = false;
	}// 0：ACC关 1： ACC开
	if((b[7]&0x2)!=0){
		res.valid = 1;
	}else{
		res.valid = 0;
	}// 0：未定: 1： 定位
	if((b[7]&0x4)==0){// 0北纬，1南纬
		res.latitudeStatus = "北纬";
	}else{
		res.latitudeStatus = "南纬";
	}
	if((b[7]&0x8)==0){// 0东经，1西经
		res.longitudeStatus = "东经";
	}else{
		res.longitudeStatus = "西经";
	}
	if((b[7]&0x10)==0){res.isOperations = true;}// 运营状态。0为运营，1为停运
	if((b[7]&0x20)!=0){res.isEncryption = true;}// 0表示经纬度未经保密插件加密，1表示经纬度已经有保密插件进行加密
	if((b[6]&0x4)==0){res.isNormalOil = true;}// 车辆油路正常，10
	if((b[6]&0x8)==0){res.isElectricNormal = true;}// 车辆电路正常,11
	if((b[6]&0x10)==0){
		res.isDoorUnlock = true;
	}else{
		res.isDoorUnlock = false;
	}// 车门解锁，12
	//纬度8-11
	res.latitude = code.bytes2int4(b.slice(8,12))/1000000;
	//经度12-15
	res.longitude = code.bytes2int4(b.slice(12,16))/1000000;
	//高程16-17
	res.height = code.bytes2int2(b.slice(16,18));
	//速度18-19
	res.speed = code.bytes2int2(b.slice(18,20))/10;
	//方向20-21
	res.way = code.bytes2int2(b.slice(20,22));
	//时间22-27
	res.g_time = moment(code.str2Date(code.bcd2Str(b.slice(22,28)))).format("YYYY-MM-DD HH:mm:ss");
	console.log("上传时间"+code.str2Date(code.bcd2Str(b.slice(22,28)))+"    "+res.g_time);
	if(res.g_time == "0000-00-00 00:00:00"){
		res.g_time = moment(new Date()).format("YYYY-MM-DD HH:mm:ss")
	}
	//附加信息28+
	//里程
	res.mileage = code.bytes2int4(b.slice(28,32))/10;

    //坐标转换 加密
    var gcjPosition = wgs84togcj02(res.longitude,res.latitude);
    res.longitude_e = gcjPosition.lon;
    res.latitude_e = gcjPosition.lat;
	res.writetime = moment().format("YYYY-MM-DD HH:mm:ss");           // 进入平台时间
	res.onoff = 1;


    // // 实时信息推送前端
	// io.sockets.on('connection', function (socket) {
	// 	  socket.emit('real_locations',res);
	// });

	async.series([
		function(callback){
			request('http://api.map.baidu.com/geoconv/v1/?ak=z06KS6utlnLPehgiaMS4VWqw&from=1&to=5&coords='+ res.longitude + ','
				+ res.latitude + '&output=json', function (error, response, body) {
				if (!error && response.statusCode == 200) {
					var bdCoordinateJson = JSON.parse(body);
					//console.log(bdCoordinateJson);
					res.longitude_b = bdCoordinateJson.result[0].x;
					res.latitude_b = bdCoordinateJson.result[0].y;
					callback(null, bdCoordinateJson.result[0]);
				}
			})
		},
		function(callback){
			request('http://api.map.baidu.com/geocoder/v2/?ak=z06KS6utlnLPehgiaMS4VWqw&callback=renderReverse&location='+ res.latitude_b + ','
				+ res.longitude_b + '&output=json&pois=0', function (error, response, body) {
				if (!error && response.statusCode == 200) {
					var bdLocation = body.slice(29, body.length-1);
					var bdLocationJson = JSON.parse(bdLocation);
					//console.log(bdLocationJson);
					res.location = bdLocationJson.result.formatted_address;
					callback(null, res.location);
				}
			})
		}
	],function(err, results) {
		//向后台发送udp；
		var sendUdp = true;
		for(var vehicle_data in vehicle_datas){
			if((vehicle_data.unificationcode == res.unificationcode) && (vehicle_datas.lon_b == res.longitude_b)
				&& (vehicle_datas.lat_b == res.latitude_b)){
				sendUdp = false;
			}
		}

		if((sendUdp == true) && (res.longitude_b > 50)&&(res.latitude_b > 10)){
			//console.log(res.unificationcode+'发送udp'+ res.longitude_b +","+ res.latitude_b );
			var socket = dgram.createSocket("udp4");
			socket.bind(function () {
				socket.setBroadcast(true);
			});
			var udpData = "H" + res.unificationcode
				+ "&" + res.g_time + "&"
				+ res.location + "&"
				+ res.way + "&" + res.longitude_b
				+ "&" + res.latitude_b + "T"
			var message = new Buffer(udpData);

			socket.send(message, 0, message.length, 8077, '192.168.1.3', function(err, bytes) {
				socket.close();
			});
		}

		var vehicle_data = {};
		vehicle_data.lon_b = res.longitude_b;
		vehicle_data.lat_b = res.latitude_b;
		vehicle_data.unificationcode = res.unificationcode;
		vehicle_datas.push(vehicle_data);

		if((res.latitude_b == null)||(res.longitude_b == null)){
			res.latitude_b = res.latitude_e;
			res.longitude_b = res.longitude_e;
		}

		db.gps_info.upsert(res);
	});

	var response = code.makeMessage(
		[0x80,0x01],
		code.str2Bcd(head.TerminalPhoneNum),
		code.getSerialNumber(),
		[].concat(
			code.int2bytes2(head.MsgNumber),
			[0x02,0x00],
			0x00
		)
	);
	return response;
};

module.exports = {
	parsePosition : parsePosition,
	sim_unicode_cache:sim_unicode_cache
};

//位置坐标转换
var wgs84togcj02 = function(lon,lat){
	var PI = 3.1415926535897932384626;
	var a = 6378245.0;
	var ee = 0.00669342162296594323;
	var out_of_china = function(lon, lat) {
		return (lon < 72.004 || lon > 137.8347) || ((lat < 0.8293 || lat > 55.8271) || false);
	};
	var transformlat = function (lng, lat) {
		var ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
		ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
		ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0;
		ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0;
		return ret
	};
	var transformlng = function (lng, lat) {
		var ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
		ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0;
		ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0;
		ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0;
		return ret
	};
	if (out_of_china(lon, lat)) {
		return {lon:lon, lat:lat};
	}else {
		var dlat = transformlat(lon - 105.0, lat - 35.0);
		var dlng = transformlng(lon - 105.0, lat - 35.0);
		var radlat = lat / 180.0 * PI;
		var magic = Math.sin(radlat);
		magic = 1 - ee * magic * magic;
		var sqrtmagic = Math.sqrt(magic);
		dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI);
		dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI);
		var mglat = lat + dlat;
		var mglng = lon + dlng;
		return {lon:mglng, lat:mglat};
	}
};
/*
作者：刘梦楠
功能：解析位置信息
未完：附加信息的解析
*/